package com.smartnsoft.fractory;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.smartnsoft.droid4me.app.AppPublics;
import com.smartnsoft.droid4me.app.SmartActivity;
import com.smartnsoft.droid4me.cache.Values.CacheException;
import com.smartnsoft.fractory.MyProjectGallery.HardGallery;
import com.smartnsoft.fractory.MyProjectGallery.PageView;
import com.smartnsoft.fractory.bo.Project;
import com.smartnsoft.fractory.ws.FractoryServices;

/**
 * The project selector screen.
 * 
 * @author Willy Noel
 * @since 2011.05.25
 */

public final class MyProjectActivity
    extends SmartActivity<Void>
    implements View.OnClickListener
{
  private MyProjectGallery.HardGallery gallery;

  private String pathBitmap;

  private int currentPositionOntheGallery;

  private SeekBar pageViewSeekBar;

  private MyProjectGallery.PageView pageViewSquare;

  private List<Project> projects;

  private TextView projectName;

  private TextView projectExpression;

  private TextView projectDate;

  private ImageButton openProjectButton;

  private ImageButton deleteProjectButton;

  private ImageButton setAsWallpaperProjectButton;

  private Project projectSelected;

  private Context context = this;

  public void onRetrieveDisplayObjects()
  {
    setContentView(R.layout.myproject_screen);
    gallery = (HardGallery) findViewById(R.id.gallery);
    pageViewSeekBar = (SeekBar) findViewById(R.id.pageViewSeekBar);
    pageViewSquare = (PageView) findViewById(R.id.pageViewSquare);
    projectName = (TextView) findViewById(R.id.projectName);
    projectExpression = (TextView) findViewById(R.id.projectExpression);
    projectDate = (TextView) findViewById(R.id.projectDate);
    openProjectButton = (ImageButton) findViewById(R.id.projectOpenButton);
    deleteProjectButton = (ImageButton) findViewById(R.id.projectDeleteButton);
    setAsWallpaperProjectButton = (ImageButton) findViewById(R.id.projectSetAsWallpaperButton);

    openProjectButton.setOnClickListener(this);
    deleteProjectButton.setOnClickListener(this);
    setAsWallpaperProjectButton.setOnClickListener(this);
    gallery.setDisableRequestLayout(true);

  }

  public void onRetrieveBusinessObjects()
      throws BusinessObjectUnavailableException
  {
    try
    {
      projects = FractoryServices.getInstance().getProjects();
    }
    catch (CacheException exception)
    {
      throw new BusinessObjectUnavailableException(exception);
    }

  }

  public void onFulfillDisplayObjects()
  {
    gallery.setAdapter(new GalleryAdapter());

    if (showSquare())
    {
      pageViewSquare.setPagesCount(projects.size(), R.drawable.page_view_dot, (int) this.getResources().getDimension(R.dimen.dotEdge));
      pageViewSquare.setVisibility(View.VISIBLE);
      pageViewSeekBar.setVisibility(View.GONE);
    }
    else if (showSeekBar())
    {
      pageViewSeekBar.setMax(projects.size() - 1);
      pageViewSquare.setVisibility(View.GONE);
      pageViewSeekBar.setVisibility(View.VISIBLE);
    }
    else
    {
      pageViewSquare.setVisibility(View.GONE);
      pageViewSeekBar.setVisibility(View.GONE);
    }
  }

  public void onSynchronizeDisplayObjects()
  {
    gallery.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
    {
      public void onItemSelected(AdapterView<?> adaptater, View view,
          final int position, long id)
      {
        synchronized (projects)
        {
          currentPositionOntheGallery = position;
          projectSelected = projects.get(position);
          projectName.setText(projects.get(position).name);
          projectExpression.setText(projects.get(position).expression);
          projectDate.setText(projects.get(position).date.toLocaleString());
          pathBitmap = projects.get(position).pathBitmap;
        }
      }

      public void onNothingSelected(AdapterView<?> adaptater)
      {

      }
    });

  }

  private boolean showSquare()
  {
    return projects.size() >= 2 && projects.size() < 6;
  }

  private boolean showSeekBar()
  {
    return projects.size() >= 2 && projects.size() >= 6;
  }

  public class GalleryAdapter
      extends BaseAdapter
  {

    private Handler handler;

    public int getCount()
    {
      return projects.size();
    }

    public Object getItem(int position)
    {
      return projects.get(position);
    }

    public long getItemId(int position)
    {
      return 0;
    }

    @Override
    public boolean isEnabled(int position)
    {
      return true;
    }

    public View getView(int position, View convertView, ViewGroup parent)
    {
      // final int actualPostion = position % projects.size();
      final View view;
      if (convertView == null)
      {
        view = LayoutInflater.from(parent.getContext()).inflate(R.layout.myproject_gallery_screen, null);
        view.setLayoutParams(new Gallery.LayoutParams(parent.getWidth() <= 0 ? LayoutParams.FILL_PARENT
            : parent.getWidth(), (int) view.getResources().getDimension(R.dimen.articlePictureHeight)));
      }
      else
      {
        view = convertView;
      }
      final ImageView picture = (ImageView) view.findViewById(R.id.picture);

      if (handler == null)
      {
        handler = new Handler();
      }
      picture.setImageBitmap(BitmapFactory.decodeFile(projects.get(position).pathBitmap));
      return view;
    }
  }

  public void onClick(View view)
  {
    if (openProjectButton == view)
    {
      startActivity(new Intent(this, EditorActivity.class).putExtra(EditorActivity.PROJECT, projectSelected));
      this.finish();

    }
    if (deleteProjectButton == view)
    {
      // gallery.removeViewAt(currentPositionOntheGallery);
      AppPublics.LOW_PRIORITY_THREAD_POOL.execute((Activity) context, new Runnable()
      {

        public void run()
        {

          FractoryServices.getInstance().removeProjects(projectSelected);
          refreshBusinessObjectsAndDisplay();
        }
      });

      (this).runOnUiThread(new Runnable()
      {
        public void run()
        {
          Toast.makeText(getApplicationContext(), "Project deleted", Toast.LENGTH_SHORT);
        }
      });

    }
    if (setAsWallpaperProjectButton == view)
    {
      Bitmap image = BitmapFactory.decodeFile(pathBitmap);
      new FractalFeed(this, image).setAsWallpaper(getHandler());

    }

  }
}
